package com.cssy.yd.logic.web;

import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.service.IBasicPlaceofstorageService;
import com.cssy.yd.basic.service.IBasicStorageService;
import com.cssy.yd.logic.entity.LogicPoDO;
import com.cssy.yd.logic.entity.LogicPoReturnDO;
import com.cssy.yd.logic.entity.LogicPoReturnItemBatchDO;
import com.cssy.yd.logic.entity.LogicPoReturnItemDO;
import com.cssy.yd.logic.entity.LogicPoWareDO;
import com.cssy.yd.logic.entity.LogicPoWareItemBatchDO;
import com.cssy.yd.logic.entity.LogicPoWareItemDO;
import com.cssy.yd.logic.service.ILogicPoReturnItemBatchService;
import com.cssy.yd.logic.service.ILogicPoReturnService;
import com.cssy.yd.logic.service.ILogicPoService;
import com.cssy.yd.logic.service.ILogicPoWareService;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Controller
@RequestMapping("/yd/logic/poreturn")
public class PoReturnController extends BaseController<LogicPoReturnDO> {
	private static final String MANAGER = "/yd/logic/poreturn/PoReturnManager";// 列表页面
	private static final String EIDT = "/yd/logic/poreturn/PoReturnOperation";// 添加、修改、显示页面
	private static final String ITEMMANAGER = "/yd/logic/poreturn/ItemManager";// 添加、修改、显示页面

	@Resource(name = "logicPoService")
	private ILogicPoService logicPoService;
	
	@Resource(name = "logicPoReturnService")
	private ILogicPoReturnService logicPoReturnService;

	@Resource(name = "logicPoWareService")
	private ILogicPoWareService logicPoWareService;

	@Resource(name = "basicwhService")
	private IBasicStorageService basicwhService;

	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;

	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;
	
	@Resource(name="logicPoReturnItemBatchService")
	private ILogicPoReturnItemBatchService logicPoReturnItemBatchService;
	
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return MANAGER;
	}

	@RequestMapping(value="itemManager")
	public String itemManager(HttpServletRequest request, Model model)
			throws Exception {
		String itemdata =request.getParameter("data");
		String billstatus =request.getParameter("billstatus");
		String updstatus =request.getParameter("updstatus");
		LogicPoReturnItemDO logicPoReturnItemDO=JSONArray.parseObject(new String(itemdata.getBytes("ISO-8859-1"),"UTF-8"), LogicPoReturnItemDO.class);
		if(logicPoReturnItemDO.getItemBatch() != null & !"".equals(logicPoReturnItemDO.getItemBatch())){
			request.setAttribute("itemBatchDOs", logicPoReturnItemDO.getItemBatch());
		}
		request.setAttribute("updstatus", updstatus);
		request.setAttribute("billstatus", billstatus);
		return ITEMMANAGER;
	}
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		Map<String,Object> sqlMap = SqlUtil.sqlUtil.roleWhSqlFilter(request, scUserRolePlaceService,"whcode");
		scs.addCondition((String)sqlMap.get("option"), (List)sqlMap.get("roleWhList"));
		//scs.addCondition("billtype","1",SearchCondition.OP_EQUAL);
		scs.setOrderBy("dctime desc");
		SearchResult result = logicPoReturnService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);

	}
	@RequestMapping(value = "/itemlist")
	public void itemlist(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String itembatch =request.getParameter("itembatch");
		String updstatus = request.getParameter("updstatus");
		SearchResult result= new SearchResult();
		List<LogicPoReturnItemBatchDO> batchDOs = new ArrayList<LogicPoReturnItemBatchDO>();
		if("1".equals(updstatus)){
			if(itembatch != null  && !"".equals(itembatch)){
				batchDOs=JSONArray.parseArray(new String(itembatch.getBytes("ISO-8859-1"),"UTF-8"), LogicPoReturnItemBatchDO.class);
			}
		}else{
			List<LogicPoWareItemBatchDO> itemBatchDOs=null;
			if(itembatch != null  && !"".equals(itembatch)){
				itemBatchDOs=JSONArray.parseArray(new String(itembatch.getBytes("ISO-8859-1"),"UTF-8"), LogicPoWareItemBatchDO.class);
			}
			LogicPoReturnItemBatchDO returnItemBatchDO = null;
			if(itemBatchDOs != null && itemBatchDOs.size() > 0){
				for (LogicPoWareItemBatchDO logicPoWareItemBatchDO : itemBatchDOs) {
					if((logicPoWareItemBatchDO.getJreturnCount()==null?0.0:logicPoWareItemBatchDO.getJreturnCount()) < (logicPoWareItemBatchDO.getJquantity()==null?0.0:logicPoWareItemBatchDO.getJquantity())){
					returnItemBatchDO = new LogicPoReturnItemBatchDO();
					returnItemBatchDO.setMaterialsid(logicPoWareItemBatchDO.getMaterialsid());
					returnItemBatchDO.setCode(logicPoWareItemBatchDO.getCode());
					returnItemBatchDO.setName(logicPoWareItemBatchDO.getName());
					returnItemBatchDO.setUnit(logicPoWareItemBatchDO.getUnit());
					returnItemBatchDO.setQuantity(logicPoWareItemBatchDO.getBadcount());
					returnItemBatchDO.setJunit(logicPoWareItemBatchDO.getJunit());
					returnItemBatchDO.setJquantity(logicPoWareItemBatchDO.getHealthycount());
					returnItemBatchDO.setSpec(logicPoWareItemBatchDO.getSpec());
					returnItemBatchDO.setBatch(logicPoWareItemBatchDO.getBatch());
					returnItemBatchDO.setState(logicPoWareItemBatchDO.getState());
					returnItemBatchDO.setJhealthycount(logicPoWareItemBatchDO.getJquantity());
					returnItemBatchDO.setHealthycount(logicPoWareItemBatchDO.getQuantity());
					returnItemBatchDO.setJbadcount(logicPoWareItemBatchDO.getJreturnCount());
					returnItemBatchDO.setBadcount(logicPoWareItemBatchDO.getReturnCount());
					returnItemBatchDO.setUnitconvert(logicPoWareItemBatchDO.getUnitconvert());
					batchDOs.add(returnItemBatchDO);
					}
				}
			}
		}
		result.setRecordCount(batchDOs.size());
		result.setResults(batchDOs);

		 OutJsonGrid out=new OutJsonGrid(result);
		 out.printJSon(response);
		
	}
	@RequestMapping(value = "/applyitemlist")
	public void applyitemlist(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		SearchResult result = new SearchResult();
		if (id != null && !"".equals(id)) {
			List<LogicPoReturnItemDO> prlist=new ArrayList<LogicPoReturnItemDO>();
			SearchConditions scs = new SearchConditions();
			scs.addCondition("powareid",id,SearchCondition.OP_EQUAL);
			scs.setRemovedProperty(null);
			scs.setOrderBy("code asc");
			result = logicPoWareService.findItemListByExample(scs);
			List<LogicPoReturnItemDO> itemlist=new ArrayList<LogicPoReturnItemDO>();
			if(result.getResults().size()>0){
				List<LogicPoWareItemDO> pw=result.getResults();
				for(int i=0;i<pw.size();i++){
					if(Double.parseDouble(((pw.get(i).getJquantity()==null?0.0:pw.get(i).getJquantity())+""))>Double.parseDouble((pw.get(i).getJreturnCount()==null?0.0:pw.get(i).getJreturnCount())+"")){
					LogicPoReturnItemDO pr=new LogicPoReturnItemDO();
					pr.setMaterialsid(pw.get(i).getMaterialsid());
					pr.setCode(pw.get(i).getCode());
					pr.setName(pw.get(i).getName());
					pr.setUnit(pw.get(i).getUnit());
					pr.setJunit(pw.get(i).getJunit());
					pr.setSpec(pw.get(i).getSpec());
					pr.setPrice(pw.get(i).getPrice());
					pr.setJquantity(pw.get(i).getHealthycount());
					pr.setQuantity(pw.get(i).getBadcount());
					pr.setJhealthycount(pw.get(i).getJquantity());
					pr.setHealthycount(pw.get(i).getQuantity());
					pr.setBadcount(pw.get(i).getReturnCount());
					pr.setJbadCount(pw.get(i).getJreturnCount());
					pr.setState(pw.get(i).getState());
					pr.setUnitconvert(pw.get(i).getUnitconvert());
//					pr.setBatch(pw.get(i).getBatch());
					pr.setItemBatch(pw.get(i).getItemBatchDO());
					pr.setOpenBatch(pw.get(i).getOpenBatch());
					itemlist.add(pr);
					}
				}
			}
			result.setResults(itemlist);
			result.setRecordCount(itemlist.size());
		}
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}

	@Override
	public String operationForm(HttpServletRequest request,
			@PathVariable String id, @PathVariable String flag, Model model)
			throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		model.addAttribute("polist", findpolist());
		if (OperationFlag.ADD.equals(flag)) {// 我新增加时操作
			model.addAttribute("flag", "ADD");
		} else {
			LogicPoReturnDO lrd = logicPoReturnService.findListById(id);
			/*SearchConditions scs2 = new SearchConditions();
			scs2.addCondition("returnpoid", lrd.getId(), SearchCondition.OP_EQUAL);
			scs2.setRemovedProperty(null);
			scs2.setLimitPage(false);
			scs2.setOrderBy("code asc");
			List<LogicPoReturnItemDO> lpitem = logicPoReturnService.findItemListByExample(scs2).getResults();*/
			model.addAttribute("poreturn", lrd);
			//model.addAttribute("returnitem", lpitem);
			model.addAttribute("flag", "EDIT");
		}
		return EIDT;
	}


	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicPoReturnDO lrd = logicPoReturnService.findListById(id);
			SearchConditions scs2 = new SearchConditions();
			scs2.addCondition("returnpoid", lrd.getId(), SearchCondition.OP_EQUAL);
			scs2.setRemovedProperty(null);
			scs2.setLimitPage(false);
			scs2.setOrderBy("code asc");
			List<LogicPoReturnItemDO> lpitem = logicPoReturnService.findItemListByExample(scs2).getResults();
			OutJsonGrid outone = new OutJsonGrid(lpitem);
			outone.printJSon(response);
			
		}
	}
	
	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicPoReturnDO curAP, BindingResult result, Model model)
			throws SyBaseException {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata = request.getParameter("itemdata");
		if (itemdata == null && "".equals(itemdata)) {
			bodyMap.isFail();
			bodyMap.configWebInfor("物料不能为空！");
			return bodyMap.modelMap;
		}
		Map<String, Object> map  = new HashMap<String, Object>();
		if(curAP.getPowarecode() != null && !"".equals(curAP.getPowarecode())){
			map.put("powarecode", curAP.getPowarecode());
		}
		if(curAP.getReturnpocode() != null && !"".equals(curAP.getReturnpocode())){
			map.put("returnpocode", curAP.getReturnpocode());
		}
		int count= logicPoReturnService.untreatedPoreturncode(map);
		if(count > 0 ){
			bodyMap.isFail();
			bodyMap.configWebInfor("该采购入库单有对应的退货单没有处理,请先处理!");
			return bodyMap.modelMap;
		}
		
		try {
			logicPoReturnService.returnsave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;

	}

	@RequestMapping(value = "/warelist")
	@ResponseBody
	public List warelist(HttpServletRequest request, Model model)
			throws Exception {
		String pocode = request.getParameter("pocode");
		List<LogicPoWareDO> poapplylist = new ArrayList<LogicPoWareDO>();
		List<String> ls=new ArrayList<String>();
		try {
			SearchConditions scs = new SearchConditions();
			ls.add("3");
			ls.add("4");
			scs.addCondition("billstatus", ls);
			scs.addCondition("pocode", pocode, SearchCondition.OP_EQUAL);
			scs.setOrderBy("dctime desc");
			SearchResult result = logicPoWareService.findListByExample(scs);
			if (result.getResults().size() > 0) {
				poapplylist.addAll(result.getResults());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return poapplylist;
	}
	
	@RequestMapping(value = "/warewh")
	@ResponseBody
	public LogicPoWareDO warewh(HttpServletRequest request, Model model)
			throws Exception {
		String code = request.getParameter("code");
		LogicPoWareDO lp=null;
		try {
			lp = logicPoWareService.findListById(code);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lp;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicPoReturnDO ld=logicPoReturnService.findListById(field);
				if(ld!=null){
					ld.setRemoved(Short.parseShort("1"));
					logicPoReturnService.update(ld, SessionUtil.getUser(request));
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}

	/**
	 * 获取全部入库和部分入库的采购单号
	 * @return
	 */
	private List<LogicPoDO> findpolist(){
		SearchConditions scs = new SearchConditions();
		List<String> strlist=new ArrayList<String>();
		strlist.add("4");
		strlist.add("5");
		scs.addCondition("billstatus",strlist);
		scs.setOrderBy("dctime desc");
		List<LogicPoDO> lPoDOs= logicPoService.findListByExample(scs).getResults();
		List<LogicPoDO> logicPoDOs = new ArrayList<LogicPoDO>();
		for (LogicPoDO logicPoDO : lPoDOs) {
			List<String> ls=new ArrayList<String>();
			SearchConditions scs2 = new SearchConditions();
			ls.add("3");
			ls.add("4");
			scs2.addCondition("billstatus", ls);
			scs2.addCondition("pocode", logicPoDO.getPocode(), SearchCondition.OP_EQUAL);
			SearchResult result = logicPoWareService.findListByExample(scs2);
			if(result.getResults().size()>0){
				logicPoDOs.add(logicPoDO);
			}
		}
		return logicPoDOs;
	}
	
//	@RequestMapping(value = "/updateState")
//	public void updateState(HttpServletRequest request,HttpServletResponse response)throws Exception{
//		String id = request.getParameter("rows");
//		Map<String,String> map =new HashMap<String, String>();
//		try{
//		LogicPoReturnDO lReturnDO = logicPoReturnService.findListById(id);
//		lReturnDO.setBillstatus((short)0);
//		logicPoReturnService.update(lReturnDO,  SessionUtil.getUser(request));
//		map.put("msg", "SUCCESS");
//		}catch(Exception e){
//			e.printStackTrace();
//			map.put("msg", "ERROR");
//		}
//		AjaxUtil.printJSonArr(response, JSONObject.fromObject(map).toString());
//	}
	@RequestMapping(value = "/exportExcel")
	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{
		try {
				String id = request.getParameter("id");
				LogicPoReturnDO pr=new LogicPoReturnDO();
				List<LogicPoReturnItemDO> itemlist=new ArrayList<LogicPoReturnItemDO>();
				List<LogicPoReturnItemBatchDO> itemBatchDOs=new ArrayList<LogicPoReturnItemBatchDO>();
				if(!"".equals(id)&&id!=null){
					pr =logicPoReturnService.findListById(id);
				}
				if(pr.getId()!=null){
					SearchConditions scs = new SearchConditions();
					scs.addCondition("returnpoid", pr.getId(),SearchCondition.OP_EQUAL);
					scs.setLimitPage(false);
					scs.setRemovedProperty(null);
					scs.setOrderBy("code asc");
					itemlist =logicPoReturnService.findItemListByExample(scs).getResults();
					if(itemlist!=null){
						int k = 1;
						for (LogicPoReturnItemDO logicPoReturnItemDO : itemlist) {
							SearchConditions scs2 = new SearchConditions();
							scs2.addCondition("returnItemId", logicPoReturnItemDO.getId(),SearchCondition.OP_EQUAL);
							scs2.setLimitPage(false);
							scs2.setRemovedProperty(null);
							scs2.setOrderBy("code asc");
							List<LogicPoReturnItemBatchDO> list = logicPoReturnItemBatchService.findListByExample(scs2).getResults();
							if(list!=null){
								for (LogicPoReturnItemBatchDO logicPoReturnItemBatchDO : list) {
									logicPoReturnItemBatchDO.setId(k+"");
									if(logicPoReturnItemBatchDO.getName()!=null && logicPoReturnItemBatchDO.getSpec()!=null){
										logicPoReturnItemBatchDO.setSpec(";"+logicPoReturnItemBatchDO.getSpec());
									}else{
										logicPoReturnItemBatchDO.setSpec(logicPoReturnItemBatchDO.getSpec());
									}
									itemBatchDOs.add(logicPoReturnItemBatchDO);
									k++;
								}
							}
							
						}
						for (LogicPoReturnItemDO logicPoWareItemDO : itemlist) {
							LogicPoReturnItemBatchDO batch = new LogicPoReturnItemBatchDO();
							if(!"Y".equals(logicPoWareItemDO.getOpenBatch())){
								batch.setId(k+"");
								batch.setName(logicPoWareItemDO.getName());
								if(logicPoWareItemDO.getName()!=null && logicPoWareItemDO.getSpec()!=null){
									batch.setSpec(";"+logicPoWareItemDO.getSpec());
								}else{
									batch.setSpec(logicPoWareItemDO.getSpec());
								}
								batch.setCode(logicPoWareItemDO.getCode());
								batch.setSpec(logicPoWareItemDO.getSpec());
								batch.setJunit(logicPoWareItemDO.getJunit());
								batch.setJreturnquantity(logicPoWareItemDO.getJreturnquantity());
								itemBatchDOs.add(batch);
								k++;
							}
						}
					}
				}
				if(itemBatchDOs.size()<11){
					int s = 11-itemBatchDOs.size();
					int n =itemBatchDOs.size();
					for (int i = 0; i < s; i++) {
						LogicPoReturnItemBatchDO item = new LogicPoReturnItemBatchDO();
						item.setId(n+1+i+"");
						itemBatchDOs.add(item);
					}
				}
				request.setCharacterEncoding("utf-8");
				response.setContentType("application/vnd.ms-excel;charset=utf-8"); 
//				String fileNameDisplay = "采购入库单";
//				try {
//					fileNameDisplay = new String(fileNameDisplay.getBytes("GBK"),
//							"iso-8859-1");
//				} catch (UnsupportedEncodingException e1) {
//					e1.printStackTrace();
//				}
				response.setHeader("Content-disposition", "attachment;filename="+pr.getReturnpocode()+".xls");
				OutputStream os= response.getOutputStream(); 
		//		Map<String,Object> pMap = request.getParameterMap();
		//		List<Map> data = new ArrayList<Map>();
				XLSTransformer transformer = new XLSTransformer();
			    StringBuffer file=new StringBuffer(request.getRealPath("/"));;
				file.append("/views/printer/excelTemplate/poreturn.xls");
				Map<String, Object> map = new HashMap<String,Object>();
				map.put("pr", pr);
				map.put("item", itemBatchDOs);
				Workbook book= transformer.transformXLS(new FileInputStream(file.toString()), map);    						
					book.write(os);				
					os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
